package com.fleafinder.xmlparser;

import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.List;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;

import android.util.Xml;

import com.fleafinder.CommonConstants;
import com.fleafinder.DataCenter;
import com.fleafinder.entity.Contact;
import com.fleafinder.entity.Market;


public class MarketXmlParser {
	public static final String TAG_MARKET = "marked";
	public static final String TAG_ID = "id";
	public static final String TAG_NAME = "name";
	public static final String TAG_MARKET_TYPE = "type";
	public static final String TAG_FEE_TYPE = "feetype";
	public static final String TAG_ROAD = "road";
	public static final String TAG_ZIP = "zip";
	public static final String TAG_CITY = "city";
	public static final String TAG_DATE_FROM = "datefrom";
	public static final String TAG_DATE_TO = "dateto";
	public static final String TAG_START_AT = "startat";
	public static final String TAG_END_AT = "endat";
	public static final String TAG_STANDE = "stande";
	public static final String TAG_DESC = "desc";
	public static final String TAG_CATEGORIES = "categories";
	public static final String TAG_CATEGORY = "category";
	
	public static final String TAG_CONTACT = "contact";
	public static final String TAG_CONTACT_NAME = "name";
	public static final String TAG_CONTACT_EMAIL = "email";
	public static final String TAG_CONTACT_HOMEPAGE = "homepage";
	public static final String TAG_CONTACT_PHONE = "tlf";
	public static final String TAG_CONTACT_FACEBOOK = "fb";
	public static final String TAG_CONTACT_TWITTER = "twt";
	
	public static final int I_TAG_MARKET = 0;
	public static final int I_TAG_ID = 1;
	public static final int I_TAG_NAME = 2;
	public static final int I_TAG_MARKET_TYPE = 3;
	public static final int I_TAG_FEE_TYPE = 4;
	public static final int I_TAG_ROAD = 5;
	public static final int I_TAG_ZIP = 6;
	public static final int I_TAG_CITY = 7;
	public static final int I_TAG_DATE_FROM = 8;
	public static final int I_TAG_DATE_TO = 9;
	public static final int I_TAG_START_AT = 10;
	public static final int I_TAG_END_AT = 11;
	public static final int I_TAG_STANDE = 12;
	public static final int I_TAG_DESC = 13;
	public static final int I_TAG_CATEGORIES = 14;
	public static final int I_TAG_CATEGORY = 15;
	
	public static final int I_TAG_CONTACT = 16;
	public static final int I_TAG_CONTACT_NAME = 17;
	public static final int I_TAG_CONTACT_EMAIL = 18;
	public static final int I_TAG_CONTACT_HOMEPAGE = 19;
	public static final int I_TAG_CONTACT_PHONE = 20;
	public static final int I_TAG_CONTACT_FACEBOOK = 21;
	public static final int I_TAG_CONTACT_TWITTER = 22;
	
	private List<Market> marketList = null;
	
	private Market parsedMarket = null;
	
	private int currentTag = -1;
	
	private Date today;
	
	
	/**
	 * 
	 * @param dataHolder
	 */
	public MarketXmlParser(List<Market> dataHolder){
		
		this();
		
		this.marketList = dataHolder;//new ArrayList<Market>();
	}
	
	public MarketXmlParser(){
		today = new Date();
	}
	
	/**
	 * 
	 * @return
	 */
	public List<Market> getMarketList(){
		return this.marketList;
	}
	
	/**
	 * @param in
	 * @throws XmlPullParserException
	 * @throws IOException
	 */
	public void parse(InputStream in) throws XmlPullParserException, IOException {
        try {
            XmlPullParser parser = Xml.newPullParser();
            parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false);
            parser.setInput(in, CommonConstants.ENCODING_UTF_8);
            
            readMarketList(parser);
            
        } catch(Exception e){
        	e.printStackTrace();
        } finally {
            in.close();
        }
    }

	/**
	 * 
	 * @param parser
	 * @throws IOException
	 */
	public void readMarketList(XmlPullParser parser) throws IOException{
		try {
			int tag = parser.next();

			Market m = null;
			while (tag != XmlPullParser.END_DOCUMENT) {
				if (tag == XmlPullParser.START_TAG) {
					if (TAG_MARKET.equals(parser.getName())) {
						currentTag = I_TAG_MARKET;
						m = new Market();
						
//						Log.i("1", "Start reading market id = ");

						readMarketEntry(parser, m);
						
//						Log.i("1", "Finish reading market id = " + m.getId());
						//if(m.getId() == 421){
						//	int a = 0;
						//	int b = a;
						//}
						
						Date endDate = (Date) m.getDateToObject().clone();
						endDate.setTime(endDate.getTime() + CommonConstants.MILLISECONDS_IN_DAY);
						if(m.getDateFromObject().getTime() <= today.getTime() && endDate.getTime() >= today.getTime()){
							m.setShowOnMap(true);
						}
						
						if(this.marketList != null){
							this.marketList.add(m);
							//Log.d("", "Just added one market to market list @ " + this.marketList + ": " + m.getName());
							//Log.d("debug", "Size of market list inside MarketXmlParser: " + this.marketList.size());
						} else {
							this.parsedMarket = m;
						}
					}
				}

				tag = parser.next();
			}
		} catch (XmlPullParserException ex) {
			ex.printStackTrace();
		} catch(IllegalStateException ex){
			ex.printStackTrace();
		}
	}
	
	/**
	 * @param parser
	 * @param m
	 * @return
	 * @throws XmlPullParserException
	 * @throws IOException
	 */
	@SuppressWarnings("finally")
	private Market readMarketEntry(XmlPullParser parser, Market m)
			throws IOException {
		try {
			while (true) {

				int next = parser.getEventType();

				if(next == XmlPullParser.TEXT && parser.getName() == null && currentTag == I_TAG_MARKET){
					parser.next();
					continue;
				}
				
				if (next == XmlPullParser.END_TAG) {
					if (currentTag == I_TAG_MARKET) {
						//Log.i("1", "END OF 1 MARKET");
						break;
					} else {
						currentTag = I_TAG_MARKET;
						// continue;
					}
				} else if (next == XmlPullParser.START_TAG) {
					if (TAG_MARKET.equals(parser.getName())) {
						// continue;
					} else if (TAG_ID.equals(parser.getName())) {
						currentTag = I_TAG_ID;
					} else if (TAG_NAME.equals(parser.getName())) {
						currentTag = I_TAG_NAME;
					} else if (TAG_MARKET_TYPE.equals(parser.getName())) {
						currentTag = I_TAG_MARKET_TYPE;
					} else if (TAG_FEE_TYPE.equals(parser.getName())) {
						currentTag = I_TAG_FEE_TYPE;
					} else if (TAG_ROAD.equals(parser.getName())) {
						currentTag = I_TAG_ROAD;
					} else if (TAG_ZIP.equals(parser.getName())) {
						currentTag = I_TAG_ZIP;
					} else if (TAG_CITY.equals(parser.getName())) {
						currentTag = I_TAG_CITY;
					} else if (TAG_DATE_FROM.equals(parser.getName())) {
						currentTag = I_TAG_DATE_FROM;
					} else if (TAG_DATE_TO.equals(parser.getName())) {
						currentTag = I_TAG_DATE_TO;
					} else if (TAG_START_AT.equals(parser.getName())) {
						currentTag = I_TAG_START_AT;
					} else if (TAG_END_AT.equals(parser.getName())) {
						currentTag = I_TAG_END_AT;
					} else if (TAG_STANDE.equals(parser.getName())) {
						currentTag = I_TAG_STANDE;
					} else if (TAG_DESC.equals(parser.getName())) {
						currentTag = I_TAG_DESC;
					} else if (TAG_CATEGORIES.equals(parser.getName())) {
						currentTag = I_TAG_CATEGORIES;

						CategoryXmlParser categoryParser = new CategoryXmlParser();
						categoryParser.readCategoryEntries(parser);
						m.setCategories(categoryParser.getCategoryList());
						
						currentTag = I_TAG_MARKET;

					} else if (TAG_CONTACT.equals(parser.getName())) {
						currentTag = I_TAG_CONTACT;

						Contact c = new Contact();
						readContactEntry(parser, c);
						m.setContact(c);
						
						currentTag = I_TAG_MARKET;
					}
				} else if (next == XmlPullParser.TEXT) {

					// TODO: check empty string

					if (currentTag == I_TAG_ID) {
						m.setId(Integer.parseInt(parser.getText()));
					} else if (currentTag == I_TAG_NAME) {
						m.setName(parser.getText());
//						Log.d("", "Market Name loaded: " + parser.getText());
					} else if (currentTag == I_TAG_MARKET_TYPE) {
						//m.setMarketType(parser.getText());
						m.setMarketTypeName(parser.getText());
					} else if (currentTag == I_TAG_FEE_TYPE) {
						m.setFeeType(parser.getText());
						
						if(m.getFeeType().contains(CommonConstants.PLUS_SIGN)){
							m.setBusiness(true);
						}
						
					} else if (currentTag == I_TAG_ROAD) {
						m.setRoad(parser.getText());
					} else if (currentTag == I_TAG_ZIP) {
						m.setZip(parser.getText());
					} else if (currentTag == I_TAG_CITY) {
						m.setCity(parser.getText());
					} else if (currentTag == I_TAG_DATE_FROM) {
						m.setDateFrom(parser.getText());
						
						Date dateFrom = DataCenter.getInstance().getDateFormat().parse(m.getDateFrom());
						m.setDateFromObject(dateFrom);
						
					} else if (currentTag == I_TAG_DATE_TO) {
						m.setDateTo(parser.getText());
						
						Date dateTo = DataCenter.getInstance().getDateFormat().parse(m.getDateTo());
						m.setDateToObject(dateTo);
						
						DataCenter.getInstance().formatDateOfMarket(m);
					} else if (currentTag == I_TAG_START_AT) {
						m.setStartAt(parser.getText());
					} else if (currentTag == I_TAG_END_AT) {
						m.setEndAt(parser.getText());
					} else if (currentTag == I_TAG_STANDE) {
						m.setStande(parser.getText());
					} else if (currentTag == I_TAG_DESC) {
						m.setDescription(parser.getText());
					}
				}
				parser.next();
			}
			
		} catch (XmlPullParserException ex) {
			ex.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			return m;
		}

	}

	/**
	 * 
	 * @param parser
	 * @param c
	 * @throws XmlPullParserException
	 * @throws IOException
	 */
	private void readContactEntry(XmlPullParser parser, Contact c) throws XmlPullParserException, IOException {
		while(true){
			int next = parser.getEventType();
			
			if(next == XmlPullParser.END_TAG){
				if(currentTag == I_TAG_CONTACT){
					break;
				} else {
					currentTag = I_TAG_CONTACT;
				}
			} else if(next == XmlPullParser.START_TAG){
				if(TAG_CONTACT_NAME.equals(parser.getName())){
					currentTag = I_TAG_CONTACT_NAME;
				} else if(TAG_CONTACT_EMAIL.equals(parser.getName())){
					currentTag = I_TAG_CONTACT_EMAIL;
				} else if(TAG_CONTACT_HOMEPAGE.equals(parser.getName())){
					currentTag = I_TAG_CONTACT_HOMEPAGE;
				} else if(TAG_CONTACT_PHONE.equals(parser.getName())){
					currentTag = I_TAG_CONTACT_PHONE;
				} else if(TAG_CONTACT_FACEBOOK.equals(parser.getName())){
					currentTag = I_TAG_CONTACT_FACEBOOK;
				} else if(TAG_CONTACT_TWITTER.equals(parser.getName())){
					currentTag = I_TAG_CONTACT_TWITTER;
				}
			} else if(next == XmlPullParser.TEXT){
				if(currentTag == I_TAG_CONTACT_NAME){
					c.setName(parser.getText());
				} else if(currentTag == I_TAG_CONTACT_EMAIL){
					c.setEmail(parser.getText());
				} else if(currentTag == I_TAG_CONTACT_HOMEPAGE){
					c.setHomepage(parser.getText());
				} else if(currentTag == I_TAG_CONTACT_PHONE){
					c.setPhone(parser.getText());
				} else if(currentTag == I_TAG_CONTACT_FACEBOOK){
					c.setFacebook(parser.getText());
				} else if(currentTag == I_TAG_CONTACT_TWITTER){
					c.setTwitter(parser.getText());
				}
			}
			
			parser.next();
		}
	}

	public Market getParsedMarket() {
		return parsedMarket;
	}

	public void setParsedMarket(Market parsedMarket) {
		this.parsedMarket = parsedMarket;
	}
}
